/* Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef _H_BYTEORDER_
#define _H_BYTEORDER_

#include <inttypes.h>

union __EndianTest { uint32_t mylong; unsigned char c[4]; } ;
extern union __EndianTest __endian_test ;

#define ENDIANNESS  (__endian_test.c[0])

#define _SWPE16(data)	((((data) & 0xFF00) >> 8) | (((data) & 0x00FF) << 8))
#define _SWPE32(data)	((((data) & 0xFF000000) >> 24)			  \
				| (((data) & 0x00FF0000) >> 8)		  \
				| (((data) & 0x0000FF00) << 8)		  \
				| (((data) & 0x000000FF) << 24))
#define _SWPE64(data)	((((data) & (uint64_t)(0xFF00000000000000)) >> 56)	   \
				| (((data) & (uint64_t)(0x00FF000000000000)) >> 40)  \
				| (((data) & (uint64_t)(0x0000FF0000000000)) >> 24)  \
				| (((data) & (uint64_t)(0x000000FF00000000)) >> 8)  \
				| (((data) & (uint64_t)(0x00000000FF000000)) << 8)  \
				| (((data) & (uint64_t)(0x0000000000FF0000)) << 24)  \
				| (((data) & (uint64_t)(0x000000000000FF00)) << 40)  \
				| (((data) & (uint64_t)(0x00000000000000FF)) << 56))

#define BE16TOH(data)	( (ENDIANNESS) ? (data) : _SWPE16(data))
#define BE32TOH(data)	( (ENDIANNESS) ? (data) : _SWPE32(data))
#define BE64TOH(data)	( (ENDIANNESS) ? (data) : _SWPE64(data))
#define HTOBE16(data)	(BE16TOH(data))
#define HTOBE32(data)	(BE32TOH(data))
#define HTOBE64(data)	(BE64TOH(data))

#define LE16TOH(data)	((!ENDIANNESS) ? (data) : _SWPE16(data))
#define LE32TOH(data)	((!ENDIANNESS) ? (data) : _SWPE32(data))
#define LE64TOH(data)	((!ENDIANNESS) ? (data) : _SWPE64(data))
#define HTOLE16(data)	(LE16TOH(data))
#define HTOLE32(data)	(LE32TOH(data))
#define HTOLE64(data)	(LE64TOH(data))

#define HTON16(data)	(HTOBE16(data))
#define HTON32(data)	(HTOBE32(data))
#define HTON64(data)	(HTOBE64(data))
#define NTOH16(data)	(BE16TOH(data))
#define NTOH32(data)	(BE32TOH(data))
#define NTOH64(data)	(BE64TOH(data))

#endif

